<?php
/**
 * User: aka
 * Time: 18:50
 */

namespace app\get\controller;

use app\secret\model\SignInLog;
use app\validator\users\SignIn;
use think\facade\Session;
use think\Request;

class Users
{
    private function inputSignInLog(int $user_id, string $login_ip)
    {
        $addData = array();
        $addData['user_id'] = $user_id;
        $addData['login_time'] = time();
        $addData['login_ip'] = $login_ip;
        SignInLog::create($addData);
    }

    private function saveUserSessionInfo(int $user_id, $user_account, $user_name)
    {
        Session::set('user_info.user_id', $user_id);
        Session::set('user_info.user_account', $user_account);
        Session::set('user_info.user_name', $user_name);
    }

    public function signIn(Request $request)
    {
        $validate = new SignIn();
        if (!$validate->check($request->param())) {
            return json($validate->getError());
        }else {
            $condition = array();
            $condition['account'] = $request->param('account');
            $condition['password'] = encode_password($request->param('password'));
            $data = \app\secret\model\Users::where($condition)->find();
            if ($data == null)
            {
                return json(603);
            }else{
                if ($data['state'] == 1)
                {
                    return json(604);
                }else{
                    $this->inputSignInLog($data['id'], $request->ip());
                    $this->saveUserSessionInfo($data['id'], $data['account'], $data['name']);
                    return json(200);
                }
            }
        }
    }
}